package com.zdp.netty.chapter8.server;

import com.zdp.netty.chapter8.protobuf.SubscribeReqProto;
import com.zdp.netty.chapter8.protobuf.SubscribeRespProto;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

/**
 * @Author zhengdp
 * @Description
 */
public class SubReqServerHandler extends ChannelHandlerAdapter {

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        SubscribeReqProto.SubscribeReq req = (SubscribeReqProto.SubscribeReq) msg;
        if(judge(req)) {
            System.out.println("Service accept client subscribe req : [" + req.toString() + " ]");
            ctx.writeAndFlush(buildResp(req.getSubReqId()));
        } else {
            System.err.println("Judge ERROR");
        }
    }

    private SubscribeRespProto.SubscribeResp buildResp(int subReqID) {
        SubscribeRespProto.SubscribeResp.Builder builder = SubscribeRespProto.SubscribeResp.newBuilder();
        builder.setSubReqId(subReqID);
        builder.setRespCode("0");
        builder.setDesc("Netty book order succeed,3 days later , sent to the designated adderss");
        return builder.build();
    }

    private boolean judge(SubscribeReqProto.SubscribeReq req) {
        return "ZhengDP".equalsIgnoreCase(req.getUserName());
    }
}
